import requests,os, qrcode, sys
from bs4 import BeautifulSoup
from htmldocx import HtmlToDocx
import win32com.client


domain = 'https://service.phytium.com.cn'
current_path = sys.argv[0]


def save_img(filename, content):
    obj = BeautifulSoup(content, "html.parser")
    imgs = obj.find_all('img')
    urls = []
    for img in imgs:
        if 'data-src' in str(img):
            urls.append(img['data-src'])
        else:
            urls.append(img['src'])
    i = 0
    for url in urls:
        print(f"\t正在处理第{i}个图片, 共{len(urls)}个.")
        postfix = url.split(".")[-1]
        if url.startswith('/'):
            r = requests.get(domain + url)
        elif url.startswith('http'):
            r = requests.get(url)
        else:
            print("发现无法解析的图片:")
            print(url)
            raise 0
        img_file = os.path.join(current_path,"..","temp","img",f"{filename}-{i}.{postfix}")
        with open(img_file,"wb") as f:
            f.write(r.content)
        content = content.replace(url, img_file)
        i += 1
        print(f"\t\t {url} -> {img_file}")
    return content


def format_content(content):
    print("\t 开始格式化内容.")
    obj = BeautifulSoup(content, "html.parser")
    obj.find("div", {"class":"navbar"}).decompose()
    obj.find("span", {"id": "contact"}).decompose()
    obj.find("span", {"class": "info-text"}).decompose()
    obj.find("ol", {"class": "breadcrumb"}).decompose()
    for ins in obj.find_all('img', alt="Bootstrap"):
        ins.decompose()
    filename = obj.find("h1").get_text()
    print("\t 完成格式化内容.")
    return filename, str(obj)


def add_qrcode(filename, content, url):
    print("\t 开始生成二维码并加入文档树")
    qr = qrcode.QRCode(
        version=1,
        box_size=5,
        border=1)
    qr.add_data(url)
    qr.make(fit=True)
    img = qr.make_image(fill='black', back_color='white')
    img.save(os.path.join(current_path,"..","temp","img",f"{filename}-qrcode.png"))
    obj = BeautifulSoup(content, "html.parser")
    obj.find_all("div")[-1].append(obj.new_tag('img', src=os.path.join(current_path,"..","temp","img",f"{filename}-qrcode.png")))
    obj.find_all("img")[-1].append("请扫描二维码获取本案例最新版本和更多信息")
    print("\t 二维码搞定")
    return str(obj)


def save_html(url):
    print(f"开始下载{url}")
    r = requests.get(url)
    content = r.content.decode("utf-8")
    with open("temp\\1.html","w", encoding="utf-8") as f:
        filename, content = format_content(content)
        content = save_img(filename, content)
        content = add_qrcode(filename, content, url)
        f.write(content)
    return filename


def html2word(filename):
    # new_parser = HtmlToDocx()
    # new_parser.parse_html_file('temp\\1.html', f"out\\{filename}.docx")

    word = win32com.client.Dispatch('Word.Application')
    doc = word.Documents.Add(os.path.join(current_path, "..", "temp","1.html"))
    doc.SaveAs(os.path.join(os.path.join(current_path, "..", "out",f"{filename}.doc")), FileFormat=0)
    doc.Close()
    word.Quit()
    print(f"\t {filename}.docx 弄完了")


if __name__=="__main__":
    print("="*20)
    print("word实在是不好搞, 编码和图片处理非常容易翻车.. 翻了再修吧.. 真特别费劲, 最好还是出二维码直接让用户访问新服平台吧. \n访问这里获取本程序源码和最新版本: https://gitee.com/whysgh/case2word")
    print("=" * 20)
    ids = input("输入你想下载为doc的联合解决方案id们, 用逗号隔开, 例如:4,16,100,101,191 然后按回车.\n")
    ids = ids.split(",")
    for id in ids:
        filename = save_html(f"https://service.phytium.com.cn/solution/detail/?id={id}")
        html2word(filename)
    input("搞完了, 去out目录拿结果, 可以关了本窗口了.")
